package ua.amsoft.brelok.widget;

import ua.amsoft.brelok.manager.PreferencesManager;
import ua.amsoft.brelok.manager.WidgetUpdateManager;
import ua.amsoft.brelok.service.UpdateService;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * @author Tair Mustafaiev
 */
public class BrelokWidgetProvider extends AppWidgetProvider {
    
    public static final String OPEN_MAIN_ACTIVITY = "OpenMainActivity";
    
    private static final String TAG = BrelokWidgetProvider.class.getName();
    
    @Override
    public void onUpdate(final Context context, final AppWidgetManager appWidgetManager,
            final int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        for (final int appWidgetId : appWidgetIds) {
            WidgetUpdateManager.updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }
    
    @Override
    public void onDeleted(final Context context, final int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
        final PreferencesManager settingsManager = new PreferencesManager();
        final Intent intent = new Intent(context, UpdateService.class);
        cancelAlarm(context, intent);
        context.stopService(intent);
        settingsManager.deletePrefs(context);
        Log.i(BrelokWidgetProvider.TAG, "SharedPreferences was deleted");
    }
    
    /**
     * Cancels alarm manager for current widget context
     * 
     * @param context - {@link Context}
     * @param intent - {@link Intent}
     */
    private void cancelAlarm(final Context context, final Intent intent) {
        final AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        final PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
        alarm.cancel(pendingIntent);
        Log.i(BrelokWidgetProvider.TAG, "AlarmManager for widget updating was cancelled");
    }
}
